package com.wze.wze.Controller;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.wze.wze.Aop.PasToken;
import com.wze.wze.Entity.ResultEntity;
import com.wze.wze.Entity.UserTab;
import com.wze.wze.Service.UserTabService;
import com.wze.wze.Util.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin //解决跨域
@RestController //控制器注解
@RequestMapping("/User/")//请求路径
public class UserController {
    @Resource
    RedisTool redisTool;
    @Resource//依赖注入
    UserTabService userTabService;
    @Resource
    EmailTool emailTool;
    @Resource
    TokenTool tokenTool;
    ResultEntity resultEntity = null;

    /**
     * 登录
     *
     * @param UName 用户名
     * @param Pwd   密码
     * @return 是否登录成功！
     */
    @PasToken
    @GetMapping("doLogin")
    private String doLogin(@RequestParam("UName") String UName, @RequestParam("Pwd") String Pwd) {
        resultEntity = new ResultEntity();
        resultEntity.setCode(0);
        resultEntity.setMsg(tokenTool.getToken(UName));
        try {
            UserTab userTab = userTabService.doLogin(UName, Pwd);
            if (userTab == null) {
                resultEntity.setCode(1);
                resultEntity.setMsg("账号不存在");
            }else{
                resultEntity.setCode(0);
                resultEntity.setMsg("登陆成功");
                resultEntity.setData(UName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode(9999);
            resultEntity.setMsg("系统错误，请联系管理员");
        }

        return JSONTool.getJsonTool().toJson(resultEntity);
    }
    // restful接口规范：getMapping:获取、postMapping:增加、deleteMapping:删除、putMapping:更新、


    @PasToken
    @GetMapping("doPLogin")
    private String doPLogin(@RequestParam("Phone") String Phone, @RequestParam("Pwd") String Pwd) {
        resultEntity = new ResultEntity();
        resultEntity.setCode(0);
        resultEntity.setMsg(tokenTool.getToken(Phone));
        try {
            UserTab userTab = userTabService.doPLogin(Phone, Pwd);
            if (userTab == null) {
                resultEntity.setCode(1);
                resultEntity.setMsg("账号不存在");
            }else{
                resultEntity.setCode(0);
                resultEntity.setMsg("登陆成功");
                resultEntity.setData(userTab);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode(9999);
            resultEntity.setMsg("系统错误，请联系管理员");
        }

        return JSONTool.getJsonTool().toJson(resultEntity);
    }
    /**
     * 根据id获取用户
     *
     * @param id 用户id
     * @return Json
     */
    @GetMapping("User")
    private String getUserById(@RequestParam("id") int id) {
        resultEntity = new ResultEntity();
        try {
            UserTab userTab = userTabService.getUserById(id);
            if (userTab == null) {
                resultEntity.setCode("1");
                resultEntity.setMsg("查无此人");
            } else {
                resultEntity.setCode("0");
                resultEntity.setMsg("查询成功");
                resultEntity.setData(userTab);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);

    }

    @PostMapping("User")
    private String addUser(@RequestParam("UName") String UName, @RequestParam("Pwd") String Pwd,@RequestParam("NickName") String NickName,
                           @RequestParam("Phone") String Phone,@RequestParam("Email") String Email,@RequestParam("file") MultipartFile userImgFile) {
        resultEntity = new ResultEntity();
        OSSUtil ossUtil = new OSSUtil();
        String UserImg=null;
        String FilePath="D:\\BiShe\\";//存储Excel的位置
        String SuffixName = userImgFile.getOriginalFilename().substring(userImgFile.getOriginalFilename().lastIndexOf("."));//获取文件后缀
        String FileNewName= UUID.randomUUID().toString()+SuffixName;//新的文件名
        File dest = new File(FilePath+FileNewName);//生成新的文件
        if(!dest.getParentFile().exists()){//如果路径不存在，就生成
            dest.getParentFile().mkdirs();
        }
        try{
            userImgFile.transferTo(dest);//将临时文件保存到对应的路径
        }catch (Exception e){
            e.printStackTrace();
        }
        String OSSFilePath = ossUtil.updateFile(FilePath+FileNewName,FileNewName);
        try {
            if (userTabService.addUser(UName, Pwd,NickName,Phone,Email,OSSFilePath) > 0) {
                resultEntity.setCode("0");
                resultEntity.setMsg("添加成功！");
            } else {
                resultEntity.setCode("1");
                resultEntity.setMsg("添加失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    /**
     * 修改用户信息
     *
     * @param UName 用户名
     * @param Pwd   密码
     * @param id    id号
     * @return json
     */
    @PutMapping("User")
    private String upUser(@RequestParam("UName") String UName, @RequestParam("Pwd") String Pwd,@RequestParam("NickName") String NickName,
                          @RequestParam("Phone") String Phone,@RequestParam("Email") String Email,@RequestParam("file") MultipartFile userImgFile,@RequestParam("id") int id) {
        resultEntity = new ResultEntity();
        OSSUtil ossUtil = new OSSUtil();
        String UserImg=null;
        String FilePath="D:\\BiShe\\";//存储Excel的位置
        String SuffixName = userImgFile.getOriginalFilename().substring(userImgFile.getOriginalFilename().lastIndexOf("."));//获取文件后缀
        String FileNewName= UUID.randomUUID().toString()+SuffixName;//新的文件名
        File dest = new File(FilePath+FileNewName);//生成新的文件
        if(!dest.getParentFile().exists()){//如果路径不存在，就生成
            dest.getParentFile().mkdirs();
        }
        try{
            userImgFile.transferTo(dest);//将临时文件保存到对应的路径
        }catch (Exception e){
            e.printStackTrace();
        }
        String OSSFilePath = ossUtil.updateFile(FilePath+FileNewName,FileNewName);
        try {
            UserTab userTab = new UserTab();
            userTab.setId(id);
            userTab.setPwd(Pwd);
            userTab.setUName(UName);
            userTab.setNickname(NickName);
            userTab.setPhone(Phone);
            userTab.setEmail(Email);
            userTab.setUserImg(OSSFilePath);
            if (userTabService.upUser(userTab) > 0) {
                resultEntity.setCode("0");
                resultEntity.setMsg("修改成功！");
            } else {
                resultEntity.setCode("1");
                resultEntity.setMsg("修改失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return json
     */
    @DeleteMapping("User")
    private String delUser(@RequestParam("id") int id) {
        resultEntity = new ResultEntity();
        try {
            if (userTabService.delUserById(id) > 0) {
                resultEntity.setCode("0");
                resultEntity.setMsg("删除成功！");
            } else {
                resultEntity.setCode("1");
                resultEntity.setMsg("删除失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }



    /**
     * 获取用户列表
     * @param page 起始位置
     * @param limit 页码
     * @param id 用户id
     * @param UName 用户名
     * @return resultEntity
     */
    @PasToken
    @GetMapping("UserList")
    private String UserList(
            @RequestParam("page") int page,
            @RequestParam("limit") int limit,
            @RequestParam("UName") String UName,
            @RequestParam("id") int id
    ){
        try {
            resultEntity = new ResultEntity();
            int Start = (page-1) * limit;//计算分页位置
            List<UserTab> list = userTabService.getUserList(Start,limit,id,UName);
            if(id!=-1 || !UName.equals("")){//有条件
                resultEntity.setCount(String.valueOf(list.size()));
            }else {//没有查询条件
                resultEntity.setCount(String.valueOf(userTabService.getUserCount()));
            }
            resultEntity.setCode("0");
            resultEntity.setData(list);
            resultEntity.setMsg("查询成功!");
        }catch (Exception e){
            resultEntity.setCode("1");
            resultEntity.setMsg("查询失败!"+e.getMessage());
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    @GetMapping("UserEmail")
    private String UserEmail(
            @RequestParam("Email") String Email
    ){
        resultEntity = new ResultEntity();
        try {
            UserTab userTab = userTabService.getUserByEmail(Email);
            if (userTab == null) {
                resultEntity.setCode("1");
                resultEntity.setMsg("查无此");
            } else {
                resultEntity.setCode("0");
                resultEntity.setMsg("查询成功");
                resultEntity.setData(userTab);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }


    @GetMapping("SendCode")
    private String SendCode(@RequestParam("EmailAddress") String EmailAddress){
        resultEntity = new ResultEntity();
        Jedis jedis = redisTool.getJedis();
        try {
            if(userTabService.getUserByEmail(EmailAddress)==null||userTabService.getUserByEmail(EmailAddress).equals("")){
                resultEntity.setCode(3);
                resultEntity.setMsg("用户不存在");
            }else {//用户存在
                if(jedis.exists(EmailAddress)){
                    resultEntity.setCode(1);
                    resultEntity.setMsg("请不要频繁发生验证码！");
                }else {
                    int Rad = (int)(Math.random()*8999)+1000;
                    String MesCode = "您的验证码是"+Rad+"，60秒内有效";
                    emailTool.sendMail(EmailAddress, "验证码发送", MesCode, null);
                    jedis.set(EmailAddress,MesCode);//存储
                    jedis.expire(EmailAddress,60);
                    resultEntity.setCode(0);
                    resultEntity.setMsg("发送成功！");
                    resultEntity.setData(EmailAddress);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode(9999);
            resultEntity.setMsg("系统错误，请联系管理员");
        }

        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    @PostMapping("SendCode")
    private String IsCode(
            @RequestParam("EmailAddress") String EmailAddress,
            @RequestParam("Code") String Code
    ){
        resultEntity = new ResultEntity();
        UserTab userTab = userTabService.getUserByEmail(EmailAddress);
        try {
            Jedis jedis = redisTool.getJedis();
            if(jedis.exists(EmailAddress)){
                if(jedis.get(EmailAddress).equals("您的验证码是"+Code+"，60秒内有效")){
                    resultEntity.setCode(0);
                    resultEntity.setMsg("比对成功");
                    resultEntity.setData(userTab);
                }else {
                    resultEntity.setCode(1);
                    resultEntity.setMsg("比对失败");
                }
            }else {
                resultEntity.setCode(2);
                resultEntity.setMsg("Key不存在");
            }

        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode(9999);
            resultEntity.setMsg("系统错误，请联系管理员");
        }


        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    /**
     * 修改用户信息
     * @return json
     */
    @PostMapping("addImage")
    private String addImage(@RequestParam("file") MultipartFile userImgFile) {
        resultEntity = new ResultEntity();
        OSSUtil ossUtil = new OSSUtil();
        String UserImg=null;
        String FilePath="D:\\BiShe\\";//存储Excel的位置
        String SuffixName = userImgFile.getOriginalFilename().substring(userImgFile.getOriginalFilename().lastIndexOf("."));//获取文件后缀
        String FileNewName= UUID.randomUUID().toString()+SuffixName;//新的文件名
        File dest = new File(FilePath+FileNewName);//生成新的文件
        if(!dest.getParentFile().exists()){//如果路径不存在，就生成
            dest.getParentFile().mkdirs();
        }
        try{
            userImgFile.transferTo(dest);//将临时文件保存到对应的路径
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            String OSSFilePath = ossUtil.updateFile(FilePath+FileNewName,FileNewName);
            if (!OSSFilePath.equals("") ) {
                resultEntity.setCode("0");
                resultEntity.setMsg("上传成功！");
                resultEntity.setData(OSSFilePath);
            } else {
                resultEntity.setCode("1");
                resultEntity.setMsg("上传失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }


    @GetMapping("UNUser")
    private String addUNUser(@RequestParam("UName") String UName, @RequestParam("Pwd") String Pwd,@RequestParam("NickName") String NickName,
                           @RequestParam("Phone") String Phone,@RequestParam("Email") String Email,@RequestParam("UserImage") String UserImage) {
        resultEntity = new ResultEntity();
        try {
            if (userTabService.addUser(UName, Pwd,NickName,Phone,Email,UserImage) > 0) {
                resultEntity.setCode("0");
                resultEntity.setMsg("添加成功！");
            } else {
                resultEntity.setCode("1");
                resultEntity.setMsg("添加失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg("系统错误，请联系管理员");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }
}
